//
//  FoundViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/25.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "FoundViewController.h"

#import "RankListViewController.h"
#import "UpdateViewController.h"
#import "DesignerDetailViewController.h"
#import "MessageViewController.h"
#import "MineViewController.h"

#import "SearchViewController.h"

#import "FoundListCell.h"

@interface FoundViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>{
    UIButton *messageBtn;
}

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation FoundViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self getNoteNum];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataArray = [NSMutableArray array];
    self.currentPage = 1;
    
    [self setNavBar];
    [self setTableView];
    [kNotificationCenter addObserver:self selector:@selector(headerRefresh) name:@"ReloadFoundList" object:nil];
}

- (void)dealloc {
    [kNotificationCenter removeObserver:self];
}

- (void)setNavBar {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(44) + STATUS_BAR_HEIGHT)];
    [self.view addSubview:view];
    
    UIImageView *headImage = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(4) + STATUS_BAR_HEIGHT, ScreenX375(37), ScreenX375(37))];
    [headImage sd_setImageWithURL:[NSURL URLWithString:kNSUDefaultReadKey(@"pic")] placeholderImage:nil options:SDWebImageRetryFailed];
    headImage.layer.cornerRadius = ScreenX375(18.5);
    headImage.clipsToBounds = YES;
    headImage.userInteractionEnabled = YES;
    [view addSubview:headImage];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] init];
    [tapGR addTarget:self action:@selector(turnToMine)];
    [headImage addGestureRecognizer:tapGR];
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(24), ScreenX375(21))];
    [searchBtn setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(7), ScreenX375(24))];
    
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(67), ScreenX375(10) + STATUS_BAR_HEIGHT, ScreenX375(133), ScreenX375(24))];
    searchField.placeholder = @"请输入关键字";
    searchField.font = Kfont(12);
    searchField.layer.borderWidth = 1;
    searchField.layer.cornerRadius = ScreenX375(12);
    searchField.clipsToBounds = YES;
    searchField.returnKeyType = UIReturnKeySearch;
    searchField.delegate = self;
    searchField.layer.borderColor = REXADECIMALCOLOR(@"#cccccc").CGColor;
    searchField.rightView = searchBtn;
    searchField.leftView = leftView;
    searchField.leftViewMode = UITextFieldViewModeAlways;
    searchField.rightViewMode = UITextFieldViewModeAlways;
    searchField.tag = 999;
    [view addSubview:searchField];
    
    UIButton *updateBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(206), ScreenX375(10) + STATUS_BAR_HEIGHT, ScreenX375(62), ScreenX375(24))];
    [updateBtn setTitle:@"上传海报" forState:UIControlStateNormal];
    [updateBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
    updateBtn.titleLabel.font = Kfont(12);
    updateBtn.layer.cornerRadius = ScreenX375(12);
    updateBtn.clipsToBounds = YES;
    updateBtn.layer.borderColor = REXADECIMALCOLOR(@"#cccccc").CGColor;
    updateBtn.layer.borderWidth = 1;
    [updateBtn addTarget:self action:@selector(updata) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:updateBtn];
    
    UIButton *rankBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(274), ScreenX375(10) + STATUS_BAR_HEIGHT, ScreenX375(50), ScreenX375(24))];
    [rankBtn setTitle:@"排行榜" forState:UIControlStateNormal];
    [rankBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
    rankBtn.titleLabel.font = Kfont(12);
    rankBtn.layer.cornerRadius = ScreenX375(12);
    rankBtn.clipsToBounds = YES;
    rankBtn.layer.borderColor = REXADECIMALCOLOR(@"#cccccc").CGColor;
    rankBtn.layer.borderWidth = 1;
    [rankBtn addTarget:self action:@selector(rankList) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:rankBtn];
    
    messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(32), ScreenX375(12) + STATUS_BAR_HEIGHT, ScreenX375(20), ScreenX375(22))];
    [messageBtn setImage:ImageWithName(@"消息") forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(turnToMessage) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:messageBtn];
}

- (void)getNoteNum {
    if (!kNSUDefaultReadKey(@"userId")) {
        return;
    }
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/getMassageType",REQUESTHEADER] andParameter:@{@"userId":kNSUDefaultReadKey(@"userId")} success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if ([successResponse[@"data"][@"list"] count] == 0) {
                [self->messageBtn setImage:ImageWithName(@"消息2") forState:UIControlStateNormal];
            }else {
                [self->messageBtn setImage:ImageWithName(@"消息") forState:UIControlStateNormal];
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)turnToMine {
    MineViewController *vc = [[MineViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)turnToMessage {
    MessageViewController *vc = [[MessageViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)rankList {
    RankListViewController *vc = [[RankListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)updata {
    UpdateViewController *vc = [[UpdateViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, ScreenX375(44) + STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - TAB_BAR_HEIGHT - ScreenX375(44) - STATUS_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(430);
    [self.view addSubview:self.tableView];
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 12; i++) {
        NSString *imageName = [NSString stringWithFormat:@"%d",i];
        [arr addObject:ImageWithName(imageName)];
    }
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)headerRefresh {
    _currentPage = 1;
    [self getData];
    self.tableView.mj_footer.hidden = NO;
}

- (void)footerRefresh {
    if (_currentPage <= _totalPage) {
        
        _currentPage++;
        [self getData];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }else{
        
//        [HttpManager showNoteMsg:@"已经到底啦"];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = YES;
    }
}

- (void)getData {
    
    UITextField *textField = [self.view viewWithTag:999];
    NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"pageSize":@"10",@"page":[NSNumber numberWithInteger:_currentPage],@"sort":textField.text,@"userId":kNSUDefaultReadKey(@"userId")}];
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/posterList",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if (self.currentPage == 1) {
                [self.dataArray removeAllObjects];
            }
            self.totalPage = [successResponse[@"data"][@"pages"] integerValue];
            NSError *error = nil;
            for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                FoundModel *model = [[FoundModel alloc] initWithDictionary:dic error:&error];
                [self.dataArray addObject:model];
            }
            if (self.totalPage == self.currentPage) {
                self.tableView.mj_footer.hidden = YES;
            }
            if ([successResponse[@"data"][@"list"] count] == 0) {
                [HttpManager showNoteMsg:@"暂无更多数据"];
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FoundModel *model = _dataArray[indexPath.row];
    DesignerDetailViewController *vc = [[DesignerDetailViewController alloc] init];
    vc.designerId = model.userId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FoundListCell *cell = [FoundListCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.foundModel = _dataArray[indexPath.row];
    FoundModel *model = _dataArray[indexPath.row];
    cell.concernClick = ^{
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/concern",REQUESTHEADER] andParameter:@{@"concernId":kNSUDefaultReadKey(@"userId"),@"concernedId":model.userId} success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                if ([model.isFollow integerValue]) {
                    model.isFollow = @"0";
                    [HttpManager showNoteMsg:@"取消关注成功"];
                }else {
                    model.isFollow = @"1";
                    [HttpManager showNoteMsg:@"关注成功"];
                }
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    return cell;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [self.tableView.mj_header beginRefreshing];
    
//    SearchViewController *vc = [[SearchViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    
    return NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
